package com.jinzhi.jzweb.controller;


import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.jinzhi.common.annotation.Log;
import com.jinzhi.common.base.BaseController;
import com.jinzhi.common.utils.EhCacheUtil;
import com.jinzhi.common.utils.Result;
import com.jinzhi.jzweb.domain.ExaminationBatchComDO;
import com.jinzhi.jzweb.domain.ExaminationBatchComSDO;
import com.jinzhi.jzweb.domain.StuSignUpComDO;
import com.jinzhi.jzweb.pojo.ErroeDownVo;
import com.jinzhi.jzweb.pojo.StuSignUpComPoVo;
import com.jinzhi.jzweb.pojo.StuSignUpComVo;
import com.jinzhi.jzweb.service.ExaminationAnswerSheetComService;
import com.jinzhi.jzweb.service.ExaminationBatchComSService;
import com.jinzhi.jzweb.service.ExaminationBatchComService;
import com.jinzhi.jzweb.service.StuSignUpComService;
import com.jinzhi.jzweb.utils.EasyPoiUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.*;

/**
 * 
 * <pre>
 * 考生报名   第一次加密
 * </pre>
 * <small> 2023-05-05 08:52:02 | lance</small>
 */
@Controller
@RequestMapping("/jzweb/stuSignUpComPo")
public class StuSignUpComPoController extends BaseController {
	@Autowired
	private StuSignUpComService stuSignUpComService;

	@Autowired
	private StuSignUpComService stuSignUpService;
	@Autowired
	private ExaminationBatchComService examinationBatchService;
	@Autowired
	private ExaminationAnswerSheetComService examinationAnswerSheetService;

	@Autowired
	private ExaminationBatchComSService examinationBatchComSService;

	@Log("考生重考报名")
	@PostMapping("/reExam")
	@ResponseBody
	@RequiresPermissions("jzwb:stuSignUpCom:reExam")
	public Result<String> reExam(Long id) {
		StuSignUpComDO s = stuSignUpService.selectById(id);
		s.setState(8);//将考试转态“已考完”更改为“考试中”
		stuSignUpService.updateById(s);
		Map map = new HashMap<String,String>();
		map.put("stu_sign_id", id);
		examinationAnswerSheetService.deleteByMap(map);
		return Result.ok("操作成功！");
	}


	@GetMapping()
	//@RequiresPermissions("jzweb:stuSignUpCom:stuSignUpComPo1")
	String StuSignUpCom(Integer types,Model model){
		model.addAttribute("types",types);
	    return "jzweb/stuSignUpCom/stuSignUpComPo";
	}



	@GetMapping("/stuSignUpComNum2")
	@RequiresPermissions("jzweb:stuSignUpCom:stuSignUpComNum2")
	String stuSignUpComNum2(Integer types,Model model){
		model.addAttribute("types",types);
		return "jzweb/stuSignUpCom/stuSignUpComNum2";
	}


	/**
	 * 赛场录入
	 * @param id
	 * @param model
	 * @return
	 */
	@GetMapping("/stuSignUpComEnter/{id}")
	@RequiresPermissions("jzweb:stuSignUpComPo:num1")
	String stuSignUpComEnter(@PathVariable("id") Long id,Model model){
	StuSignUpComDO stuSignUpComDO=	stuSignUpService.selectById(id);
		model.addAttribute("stuSignUpCom",stuSignUpComDO);
		return "jzweb/stuSignUpCom/enterPo";
	}

	/**
	 * 导如模板 信息
	 * @throws Exception
	 */
	@GetMapping("/exportList")
	@ResponseBody
	public void exportlist( HttpServletRequest request, HttpServletResponse responseexa) throws Exception{

		List<StuSignUpComVo> list = new LinkedList<>();
		//导出操作
		EasyPoiUtil.exportExcel(list, "选手导入模板", "选手导入模板", StuSignUpComVo.class, "选手导入模板", responseexa);

	}

		/**
         * 第一次加密选手导出信息
         *
         * @param response
         */
	@GetMapping("/downloadImportStu")
	@RequiresPermissions("jzweb:stuSignUpComPo:import1")
	@ResponseBody
	public void downloadImportTemplate(HttpServletResponse response,StuSignUpComDO stuSignUpComDTO) {
		List<StuSignUpComPoVo> list1 = new LinkedList<>();
		Wrapper<StuSignUpComDO> wrapper = new EntityWrapper<StuSignUpComDO>().orderBy("com_nums", true);
	//	wrapper.eq("types",stuSignUpComDTO.getTypes());
	List<StuSignUpComDO> list=	stuSignUpComService.selectList(wrapper);
				for(StuSignUpComDO li:list){
					StuSignUpComPoVo stuSignUpComVo=new StuSignUpComPoVo();
					stuSignUpComVo.setName(li.getName());
					stuSignUpComVo.setIdNumber(li.getIdNumber());
					stuSignUpComVo.setTicketNumber(li.getTicketNumber());
					stuSignUpComVo.setUnitName(li.getUnitName());
					if(StringUtils.isNotBlank(li.getCourt2())){
						stuSignUpComVo.setCourt(examinationBatchComSService.selectById(li.getCourt2()).getName());
					}else{
						stuSignUpComVo.setCourt("-");
					}
					stuSignUpComVo.setComNums(li.getComNums());
					stuSignUpComVo.setTeacherName(li.getTeacher());
					stuSignUpComVo.setNum1(li.getRealityNm1());
					list1.add(stuSignUpComVo);
				}

		//导出操作
		EasyPoiUtil.exportExcel(list1, "考生报名信息导出", "考生报名信息导出", StuSignUpComPoVo.class, "考生报名信息导出", response);
	}


	@ResponseBody
	@GetMapping("/list")
	@RequiresPermissions("jzweb:stuSignUpComPo:stuSignUpComPo1")
	public Result<Page<StuSignUpComDO>> list(StuSignUpComDO stuSignUpComDTO){


		Wrapper<StuSignUpComDO> wrapper=new EntityWrapper<>();

		if(StringUtils.isNotBlank(stuSignUpComDTO.getName())){
			wrapper.like("name",stuSignUpComDTO.getName());
		}
		if(StringUtils.isNotBlank(stuSignUpComDTO.getCbatchName())){
			ExaminationBatchComDO examinationBatchComDO1=	examinationBatchService.findOneByKv("name",stuSignUpComDTO.getCbatchName());

			if(examinationBatchComDO1!=null){
				wrapper.like("cbatch_id",examinationBatchComDO1.getId().toString());
			}
		}
		// 查询列表数据
		Page<StuSignUpComDO> page = stuSignUpComService.selectPage(getPage(StuSignUpComDO.class),wrapper);
		List list = new ArrayList();
		for (int i = 0; i < page.getRecords().size(); i++) {
			StuSignUpComDO obj = (StuSignUpComDO) page.getRecords().get(i);
			ExaminationBatchComDO examinationBatchComDO=examinationBatchService.selectById(obj.getCbatchId());
			ExaminationBatchComSDO examinationBatchComSDO = examinationBatchComSService.selectById(obj.getCourt2());
			if(examinationBatchComDO!=null){
				obj.setCbatchName(examinationBatchComDO.getName());
			}
			if(examinationBatchComSDO!=null){
				obj.setCourtName(examinationBatchComSDO.getName());
			}

			list.add(obj);
		}
		page.setRecords(list);
        return Result.ok(page);
	}
	
	@GetMapping("/add")
	@RequiresPermissions("jzweb:stuSignUpCom:add")
	String add(){

	    return "jzweb/stuSignUpCom/add";
	}


	@GetMapping("/edit/{id}")
	@RequiresPermissions("jzweb:stuSignUpCom:edit")
	String edit(@PathVariable("id") Long id,Model model){
		StuSignUpComDO stuSignUpCom = stuSignUpComService.selectById(id);
		model.addAttribute("stuSignUpCom", stuSignUpCom);
		return "jzweb/stuSignUpCom/edit";
	}


	@Log("添加考生报名")
	@ResponseBody
	@PostMapping("/save")
	@RequiresPermissions("jzweb:stuSignUpCom:add")
	public Result<String> save( StuSignUpComDO stuSignUpCom){
		stuSignUpCom.setTypes(stuSignUpCom.getTypes());
		stuSignUpCom.setState(3);
		stuSignUpCom.setSignUpTime(new Date());
		stuSignUpComService.insert(stuSignUpCom);
        return Result.ok();
	}
	/**
	 * 实操赛道录入
	 * @param stuSignUpCom
	 * @return
	 */
	@Log("赛场录入")
	@ResponseBody
	@RequestMapping("/updateEnter")
	@RequiresPermissions("jzweb:stuSignUpComPo:num1")
	public Result<String>  updateEnter( StuSignUpComDO stuSignUpCom){
		StuSignUpComDO stuSignUpComDO1=	stuSignUpComService.selectById(stuSignUpCom.getId());
		Wrapper<StuSignUpComDO> wrapper=new EntityWrapper<>();
		if(stuSignUpCom.getCourt2()==null){
			return  Result.fail("请录入赛道！");
		}
		if(stuSignUpCom.getRealityNm1()==null){
			return  Result.fail("请录入第一次加密！");
		}
		wrapper.eq("court2",stuSignUpCom.getCourt2());
		wrapper.eq("cbatch_id",stuSignUpComDO1.getCbatchId());
		wrapper.eq("reality_um1",stuSignUpCom.getRealityNm1().replaceAll(" ",""));
		List<StuSignUpComDO> list =	stuSignUpComService.selectList(wrapper);
		if(list.size()>0){
			for(StuSignUpComDO li:list){
				if(!li.getId().equals(stuSignUpCom.getId())){
					return  Result.fail("加密序号重复！");
				}
			}

		}
		boolean update = stuSignUpComService.updateById(stuSignUpCom);
		return update ? Result.ok() : Result.fail();
	}


	@Log("修改考生报名")
	@ResponseBody
	@RequestMapping("/update")
	@RequiresPermissions("jzweb:stuSignUpCom:edit")
	public Result<String>  update( StuSignUpComDO stuSignUpCom){

		StuSignUpComDO stuSignUpComDO1=	stuSignUpComService.selectById(stuSignUpCom.getId());

//		List<StuSignUpComDO> list =	stuSignUpComService.findByKv("num2",stuSignUpCom.getNum1(),
//				"court",stuSignUpCom.getCourt(),"cbatch_id",stuSignUpComDO1.getCbatchId());

		Wrapper<StuSignUpComDO> wrapper=new EntityWrapper<>();
		wrapper.eq("court2",stuSignUpCom.getCourt());
		wrapper.eq("cbatch_id",stuSignUpComDO1.getCbatchId());
		wrapper.eq("reality_um2",stuSignUpCom.getRealityNm2());
		List<StuSignUpComDO> list =	stuSignUpComService.selectList(wrapper);
		if(list.size()>0){
			for(StuSignUpComDO li:list){
				if(!li.getId().equals(stuSignUpCom.getId())){
					return  Result.fail("加密序号重复！");
				}
			}

		}

		boolean update = stuSignUpComService.updateById(stuSignUpCom);
		return update ? Result.ok() : Result.fail();
	}
	
	@Log("删除考生报名")
	@PostMapping( "/remove")
	@ResponseBody
	@RequiresPermissions("jzweb:stuSignUpCom:remove")
	public Result<String>  remove( Long id){
		stuSignUpComService.deleteById(id);
        return Result.ok();
	}
	
	@Log("批量删除考生报名")
	@PostMapping( "/batchRemove")
	@ResponseBody
	@RequiresPermissions("jzweb:stuSignUpCom:batchRemove")
	public Result<String>  remove(@RequestParam("ids[]") Long[] ids){
		stuSignUpComService.deleteBatchIds(Arrays.asList(ids));
		return Result.ok();
	}


	/**
	 * 导出错误信息
	 *
	 * @param request
	 * @param response
	 * @throws Exception
	 * @author kl
	 */
	@Log("导出错误信息")
	@GetMapping("/importComError")
	@ResponseBody
	@Transactional
	@RequiresPermissions("jzweb:stuSignUpCom:import")
	public void download(HttpServletRequest request, HttpServletResponse response) throws Exception {
		// 告诉浏览器用什么软件可以打开此文件
		response.setHeader("content-Type", "application/vnd.ms-excel");
		// 下载文件的默认名称
		response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("考生报名导入错误信息", "UTF-8") + ".xls");
		//编码
		response.setCharacterEncoding("UTF-8");
		String jsonArray = EhCacheUtil.get("stuSignUpComPo" + this.getUserId()).toString();
		JSONArray arrayList = JSONArray.parseArray(jsonArray);
		//转换为目标对象list
		List<ErroeDownVo> groupList = JSONObject.parseArray(arrayList.toJSONString(), ErroeDownVo.class);
		Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(), ErroeDownVo.class, groupList);
		workbook.write(response.getOutputStream());
	}




}
